#!/bin/bash
#Size of pages in KB
usage()
{
cat << EOF
OPTIONS:
  -s GIGABYTES	Reserve GIGABYTES of hugepage memory
  -c		Read GIGABYTES amount from vlbistreamer default config
EOF
}
SCRIPTNAME=init_hugepages
scriptPath=${0%$SCRIPTNAME}
if [ -z "$scriptPath" ]
then
  #invoked from PATH
  scriptPath=$(which $0)
  scriptPath=${scriptPath%$SCRIPTNAME}
fi
source ${scriptPath}vbs_common_functions

HUGESIZE=$(cat /proc/meminfo | grep Hugepagesize | cut -d ' ' -f 8)
#Shown in KB
#HUGESIZE=$(($HUGESIZE*1024))
#Buffer size in GB
BUFFERSIZE=12

#Ok not using the set hugesize

n=1
#-------------------------------------------------------------------------------
#  Parse options
#-------------------------------------------------------------------------------
while [ $# -gt 0 ]
do
  case $1 in
    -s)
      BUFFERSIZE=$2
      shift
      ;;
    -c)
      BUFFERSIZE=$(get_maxmem)
      if [ ! "$?" == "$AOK" ]
      then
	echo "Error in getting maxmem"
	exit -1
      fi
      ;;
    -*) echo "Unknown argument $1";usage;exit 1;;
  *) eval "arg_$n=$1";n=$(($n+1));;
esac
shift
done



#If given param 1, its the user
if [ ! -z "$arg_1" ]
then
  USER=$arg_1
fi
#Check if user is set at all

if [ "$USER" = "replaceme" ] ; then
  echo "Please give streamer uid as parameters"
  echo "Or let make install place ./configure --enable-user=<user> here"
  exit 1
fi

#if given param 2, its the group
if [ ! -z "$arg_2" ]
then
  GROUP=$arg_2
fi
if [ "$GROUP" = "replaceme" ] ; then
  echo "Not setting gid"
  THE_GID=$(getent group $USER | cut -d: -f3)
else
  THE_GID=$(getent group $GROUP | cut -d: -f3)
fi
THE_USER_ID=$(id -u $USER)

NR_HUGE=$(((BUFFERSIZE*1024*1024)/HUGESIZE))
echo "Setting and creating $NR_HUGE of $HUGESIZE KB pages"
HAVE=`cat /proc/sys/vm/nr_hugepages`
if [ "$NR_HUGE" != "$GOT" ]
then
  echo $NR_HUGE > /proc/sys/vm/nr_hugepages
  GOT=`cat /proc/sys/vm/nr_hugepages`
  if [ "$NR_HUGE" != "$GOT" ]
  then
    echo "Could only reserve $GOT hugepages."
    echo "Memory is most likely too fragmented. Recomended use:"
    echo "Set vm.nr_hugepages = $NR_HUGE in to /etc/sysctl.conf"
  fi
fi
if [ ! -d "/mnt/huge" ]
then
  mkdir /mnt/huge
fi

mount -t hugetlbfs -o uid=$THE_USER_ID,gid=$THE_GID,mode=0755,size=${BUFFERSIZE}G none /mnt/huge
exit 0
